﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using Crm2011.Framework.Core;



namespace ScriptEase
{
    /// <summary>
    /// Provides standard functionality to resolve file synchronization conflicts.
    /// </summary>
    public static class ConflictResolver
    {
        public delegate FileSyncStatus ResolutionHandler(string mappedFilePath, WebResource webResource);


        /// <summary>
        /// Overrides the local file content with the WebResource content.
        /// </summary>
        /// <param name="filePath">The mapped file path.</param>
        /// <param name="webResource">The web resource.</param>
        /// <returns></returns>
        public static FileSyncStatus OverrideLocal(string filePath, WebResource webResource)
        {
            Trace.Default.Info("Overriding local file with web resource {0} content.", webResource.Name);
            string directory = Path.GetDirectoryName(filePath);
            if (directory != null && !Directory.Exists(directory)) Directory.CreateDirectory(directory);

            File.WriteAllText(filePath, webResource.Content != null ? FileEncoding.DecodeFrom64(webResource.Content) : String.Empty);
            return FileSyncStatus.Published;
        }



        /// <summary>
        /// Leave existing, local file intact and write the web resource content to 
        /// a new file with the name &lt;filename&gt;.CRM.js.
        /// </summary>
        /// <param name="filePath">The mapped file path.</param>
        /// <param name="webResource">The web resource.</param>
        /// <returns></returns>
        public static FileSyncStatus CreateMergeFile(string filePath, WebResource webResource)
        {
            var mergeFilePath = GetMergeFileName(filePath);
            Trace.Default.Info("Creating merge file '{0}'.", mergeFilePath);
            File.WriteAllText(mergeFilePath, webResource.Content != null ? FileEncoding.DecodeFrom64(webResource.Content) : String.Empty, Encoding.UTF8);
            return FileSyncStatus.Conflict;
        }



        public static string GetMergeFileName(string filePath)
        {
            string mergeFileName = Path.GetFileNameWithoutExtension(filePath) + ".CRM";
            string directory = Path.GetDirectoryName(filePath);
            Debug.Assert(directory != null, "directory==null!");
            return Path.Combine(directory, mergeFileName + Path.GetExtension(filePath));
        }
    }
}